<template> 
  <el-card
    class="form-container"
    shadow="never"
  >
    <el-form
      :model="admin"
      :rules="loginRules"
      ref="adminFrom"

      label-width="150px"
    >
      <el-form-item
        label="用户昵称："
        prop="nickName"
      >
        <el-input v-model="admin.nickName"></el-input>
      </el-form-item>
      <el-form-item
        label="用户名："
        prop="username"
      >
        <el-input
          v-model="admin.username"
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="密码："
        v-if = 'isEdit'
        prop="validatePass"
      >
        <el-input

          v-model="password"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item
        label="密码："
        v-if = '!isEdit'
        prop="validatePass"
      >
        <el-input
          v-model="admin.password"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item
        label="邮箱："
        prop="email"
      >
        <el-input v-model="admin.email"></el-input>
      </el-form-item>
      <!-- <el-form-item label="图像：" prop="icon">
        <single-upload v-model="admin.icon"></single-upload>
      </el-form-item> -->
      <!-- <el-form-item
        label="角色："
        prop="roleIds"
      >
        <el-checkbox-group v-model="allRoles1">
          <el-checkbox
            v-for="(item,index) in allRoles"
            :key="index"
            :checked="item.status == 1"
            :label="item.id"
          >{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->
      <el-form-item
        prop="remark"
        label="备注：">
        <el-input
          placeholder="请输入内容"
          type="textarea"
          v-model="admin.note"
          :autosize="true"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit('adminFrom')"
        >提交</el-button>
        <el-button
          v-if="!isEdit"
          @click="resetForm('adminFrom')"
        >重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import {
  createAdmin,
  getAdmin,
  updateAdmin,
  updateAdminRole,
  userRoles,
  checkPermission
} from "@/api/sys/admin";
import { isvalidUsername } from "@/utils/validate";
import { fetchList } from "@/api/sys/role";
import SingleUpload from "@/components/Upload/singleUpload";
const defaultAdmin = {
  username: "",
  roleIds: ""
};
export default {
  name: "AdminDetail",
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {

    var username = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'));
      } else if (value.length <= 20 && value.length>=2) {
        let reg =  /^[a-zA-Z\u4e00-\u9fa5]+$/
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的用户名'));
        }
      } else {
        callback(new Error('用户名长度在 2 到 20 个字符'));
      }
    };

    var nickName = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (value.length <= 20 && value.length>=2) {
        let reg =  /^[a-zA-Z\u4e00-\u9fa5]+$/
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的用户昵称'));
        }
      } else {
        callback(new Error('用户昵称长度在 2 到 20 个字符'));
      }
    };

    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    var email = (rule, value, callback) => {
      if (!value) {
        callback();
      }
      else if (value.length <= 20 && value.length>=6) {
        let reg =  /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的邮箱'));
        }
      } else {
        callback(new Error('邮箱长度在 6到 20 个字符'));
      }
    };
    // const validatePass = (rule, value, callback) => {
    //   if (this.isEdit) {
    //     if (this.password.length < 6) {
    //       callback(new Error("密码不能小于6位"));
    //     } else {
    //       callback();
    //     }
    //   } else {
    //     if (this.admin.password.length < 6) {
    //       callback(new Error("密码不能小于6位"));
    //     } else {
    //       callback();
    //     }
    //   }


    // };
    return {
      admin: Object.assign({}, defaultAdmin),
      allRoles: null,
      userRoles: null,
      roleIds: null,
      password: '',
      listQuery: {
        pageNum: 1,
        pageSize: 100
      },
      loginRules: {
         username: [   // 用户名
            {required: true, validator: username, trigger: 'blur' }
          ],
          nickName: [   // 用户昵称
            {validator: nickName, trigger: 'blur' }
          ],
        // validatePass:[
        //    { validator: validatePass, trigger: 'blur' }
        // ],
        email:[
           { validator: email, trigger: 'blur'}
        ],
        // remark:[
        //   { min: 3, max: 200, message: '备注最多200字符', trigger: 'blur' }
        // ]
      }
    };
  },
  created() {
    if (this.isEdit) {
      this.listQuery.adminId = this.$route.query.id;
      checkPermission(this.listQuery.adminId).then(res => {
        if (res.code == 200) {
          this.allRoles = res.data;
        }
      });

      getAdmin(this.$route.query.id).then(response => {
        this.admin = response.data;
      });

    } else {
      fetchList(this.listQuery).then(response => {
        response.data.forEach( (item)=>{
          item.status = 0
        })
        this.allRoles = response.data;
      });
      this.admin = Object.assign({}, defaultAdmin);
    }
  },
  computed: {
    //选中的服务保证
    allRoles1: {
      get() {
        let list = [];
        if (
          this.roleIds === undefined ||
          this.roleIds == null ||
          this.roleIds === ""
        )
          return list;
        let ids = this.roleIds.split(",");
        for (let i = 0; i < ids.length; i++) {
          list.push(Number(ids[i]));
        }
        return list;
      },
      set(newValue) {
        let serviceIds = "";
        if (newValue != null && newValue.length > 0) {
          for (let i = 0; i < newValue.length; i++) {
            serviceIds += newValue[i] + ",";
          }
          if (serviceIds.endsWith(",")) {
            serviceIds = serviceIds.substr(0, serviceIds.length - 1);
          }
          this.roleIds = serviceIds;
        } else {
          this.roleIds = null;
        }
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm("是否提交数据", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (this.isEdit) {
              if ( this.password ) {
                this.admin.password = this.password
              } else {
                delete this.admin.password
              }
              this.admin.status = 1
              updateAdmin(this.$route.query.id, this.admin).then(response => {
                if (response.code == 200) {
                  let obj = {}
                  obj.roleIds = this.admin.roleIds
                  obj.adminId = this.$route.query.id
                  // return
                  // updateAdminRole(obj).then(
                  //   response => {
                  //     if (response.code == 200) {
                  //       this.$refs[formName].resetFields();
                  //       this.$message({
                  //         message: "修改成功",
                  //         type: "success",
                  //         duration: 1000
                  //       });
                        this.$router.back();
                  //     } else {
                  //       this.$message({
                  //         message: response.msg,
                  //         type: "error",
                  //         duration: 1000
                  //       });
                  //     }
                  //   }
                  // );

                  // this.$refs[formName].resetFields();
                  // this.$message({
                  //   message: "修改成功",
                  //   type: "success",
                  //   duration: 1000
                  // });
                  // this.$router.back();
                } else {
                  this.$message({
                    message: response.msg,
                    type: "error",
                    duration: 1000
                  });
                }
              });
            } else {
              createAdmin(this.admin).then(response => {
                if (response.code == 200) {
                  this.$refs[formName].resetFields();
                  // this.admin = Object.assign({}, defaultAdmin);
                  this.$message({
                    message: "提交成功",
                    type: "success",
                    duration: 1000
                  });
                  this.$router.push('/sys/admin')
                } else {
                  this.$message({
                    message: response.msg,
                    type: "error",
                    duration: 1000
                  });
                }
              });
            }
          });
        } else {
          this.$message({
            message: "验证失败",
            type: "error",
            duration: 1000
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.admin = Object.assign({}, defaultAdmin);
    }
  }
};
</script>
<style>
</style>


